package JVM;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author:谢君臣
 * @Date:2021/4/921:19
 * @version:1.0
 * @function:
 */
public class 生产者与消费者 {
    public static void main(String[] args) {
        Product1 product = new Product1();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    product.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    product.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    product.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    product.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();

    }
}

class Product {
    private int num;

    public synchronized void increase() throws InterruptedException {
        while (num > 0)
            wait();
        num++;
        System.out.println(Thread.currentThread().getName() + "线程—>" + num);
        notifyAll();
    }

    public synchronized void decrease() throws InterruptedException {
        while (num <= 0)
            wait();
        num--;
        System.out.println(Thread.currentThread().getName() + "线程—>" + num);
        notifyAll();
    }
}
class Product1 {
    private int num;
    ReentrantLock lock = new ReentrantLock();
    Condition condition_in = lock.newCondition();
    Condition condition_de = lock.newCondition();
    public void increase() throws InterruptedException {
        lock.lock();
        try {
            while (num > 0)
                condition_in.await();
            num++;
            System.out.println(Thread.currentThread().getName() + "线程—>" + num);
            condition_de.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrease() throws InterruptedException {
        lock.lock();
        try {
            while (num <= 0)
                condition_de.await();
            num--;
            System.out.println(Thread.currentThread().getName() + "线程—>" + num);
            condition_in.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
